package com.fingard.dsp.bank.directbank.ytcb11;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Date;

public class YTCB11BatPayRec extends YTCB11Base implements IBatPayRec {

    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
        retAts.reqSeqID = p_req9188.reqBatchNO;
        try {
            Date tmpDateNow = getDayCutTime(p_req9188.getPayDateTime());
            String date = Format.Date8Format.format(tmpDateNow);
            String tmpUploadFileName = "REPAY_" +  bankFront.org +"_"+ bankFront.corpNo+"_"+date+".txt";
            String tmpLocalMarkPath = getTempFileDirectory(tmpDateNow) + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);

            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本日批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_req9188.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            StringBuilder sbFileContent = new StringBuilder();
            String tmpReqHeader = MessageFormat.format("{0}|{1}", p_req9188.totalNum, p_req9188.totalAmt);
            sbFileContent.append(tmpReqHeader);
            // 文件明细
            int i = 0;
            while (p_req9188.readRecord()) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }
                i++;
                String sourceNoteCode = p_req9188.readedDetail.sourceNoteCode;
                String askNumber = p_req9188.readedDetail.askNumber;

                String oppAct = p_req9188.readedDetail.payAct;
                String oppName = p_req9188.readedDetail.payName;
                String payAmt = p_req9188.readedDetail.payAmount;
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}",  i, sourceNoteCode,"1",askNumber,oppAct, oppName, payAmt,date, p_req9188.readedDetail.reqReserved1,p_req9188.readedDetail.reqReserved2,"");
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批次文件内容:\r\n" + sbFileContent.toString());
            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString()+"\n", getCharset());
            // 上送银保通服务器
            FtpSet ftpSet = bankFront.getFtpSet("bat");

            FtpReceiver ftpReceiver = null;
            String requestType = getBankConfig().getValueAsString("requestType");
            if (requestType != null && "SFTP".equals(requestType)) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
                ftpReceiver = sftpPortClient.uploadFile("", tmpLocalMarkPath, sftpFilePath);
                sftpPortClient.disconnect();
            } else {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpReceiver = ftpPortClient.uploadFile(tmpLocalMarkPath, tmpUploadFileName);
                ftpPortClient.disconnect();
            }
            retAts.respCode = "0";
            retAts.reqSeqID = p_req9188.reqBatchNO;
            WriteBankLogLn("文件上传："+ftpReceiver.isCompleted);
            if (!ftpReceiver.isCompleted) {
                retAts.respCode = "-1";
                retAts.respInfo = ftpReceiver.connMsg;
            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                retAts.respInfo = "上传失败";
                retAts.transState = "BatchFailed";
                retAts.payInfoCode = "E9999";
            } else {
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            }
        }catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
        retAts.reqSeqID = p_req9198.reqBatchNO;
        try{
            String date = Format.Date8Format.format(p_req9198.getBgnDateTime());
            String tmpDownFileName = "REPAYRES_" +  bankFront.org +"_"+ bankFront.corpNo+"_"+date+".txt";
            String tmpRecResultFilePath = getTempFileDirectory(p_req9198.getBgnDateTime()) + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpRecResultFilePath);
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            FtpReceiver ftpReceiver = null;
            String requestType = getBankConfig().getValueAsString("requestType");
            if (requestType != null && "SFTP".equals(requestType)) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                ftpReceiver = sftpPortClient.downloadFile(tmpDownFileName, tmpRecResultFilePath);
                sftpPortClient.disconnect();
            } else {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName, tmpRecResultFilePath);
                ftpPortClient.disconnect();
            }
            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpRecResultFilePath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);

                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";
                    retAts.reqSeqID = p_req9198.reqBatchNO;

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);

                    while(true) {
                        String eachline = tmpReader.readLine();
                        if(StringHelper.isNullOrEmpty(eachline)){
                            break;
                        }
                        eachline = eachline+"1";
                        String[] bodyValues = eachline.split("\\|");
                        if (bodyValues.length == 15 ||bodyValues.length == 14) {
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            tmpRetDetail.payAct = bodyValues[4];
                            tmpRetDetail.payName = bodyValues[5];
                            tmpRetDetail.result = bodyValues[9];
                            tmpRetDetail.postScript = bodyValues[3];
                            tmpRetDetail.payAmount = bodyValues[6];
                            tmpRetDetail.payInfoCode = bodyValues[9];
                            tmpRetDetail.memo = bodyValues[10];
                            retAts.writeRetDetail(tmpRetDetail);
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "每行明细应为15列，实际为：" + bodyValues.length;
                        }

                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "回盘文件[" + tmpDownFileName + "]内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "回盘文件下载失败:" + ftpReceiver.connMsg;
            }
        }catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
